<?php
namespace app\admin\controller;
use app\admin\model\AnnounceModel;
use think\Controller;
use think\Db;
use think\Request;

// 公告控制
class Announce extends Common
{
    const BANNERFIELDS= 'banner_id,title,banner_img,describe,add_time,is_show';
    const MESSAGE = 'msg_id,title,content,remark,add_time,push_time,is_push';

    // banner 公告列表
    public function getBannerList()
    {

        $keyword = request()->param('keyword', '');
        $order_type =request()->param('order_type', 1);
        $is_show=input('is_show','all');

        $this->orderList($keyword,$order_type,$is_show);

        $this->assign([
            'keyword' => $keyword,
            'order_type'=>$order_type,
            'is_show'=>$is_show,
        ]);

        return  $this->fetch('announce/bannerList');
    }

    private function orderList($keyword = "" ,$order_type=1,$is_show='all')
    {

        $where = '';
        if ($keyword) {
            $where['title'] = ['like', "%$keyword%"];
        }

        if($order_type == 1){
            $order_type = 'add_time desc';
        }else{
            $order_type = 'add_time ';
        }
        
        if($is_show == 1){
            $where['is_show']=1;
        }else if($is_show == 2){
            $where['is_show'] = 2;
        }

        $list = Db::table('banner')->field(self::BANNERFIELDS)->where($where)->order($order_type)->paginate(10);

        $page = $list->render();
        $banner_amount = Db('banner')->count();


        $this->assign([
            'page' => $page,
            'list' => $list,
            'banner_amount' => $banner_amount
        ]);

    }

    // 新建banner消息
    public function getBannerAdd(){
        return $this->fetch('announce/bannerAdd');
    }

    public function postBannerAdd(Request $request)
    {
        if ($request->isPost()) {

            $date = input('post.');
            // 图片
            $file = $request->file('banner_img');
            if ($file) {
                
                $date['banner_img'] = handle_upload_image($file,'banner') ;

            } else{

                $this->error('图片上传失败','/announce/BannerAdd');
            }

            $date['add_time']=time();

            $bool = Db::table('banner')->insert($date);

            if ($bool) {
                 $this->success('添加成功', '/announce/BannerList');
            } else {
                $this->error('添加失败', '/announce/BannerAdd');
            }
        }
    }

    // 修改banner 
    public function getBannerEdit(){
        $id=input('id');

        $bannerInfo= AnnounceModel::getBannerInfoById($id);

        return $this->fetch('announce/bannerEdit',['info'=>AnnounceModel::handleBannerInfo($bannerInfo)]);

    }

    public function postBannerEdit()
    {
        if (request()->isPost()) {

            $banner_id= input('post.banner_id');
            $data['title'] = input('post.title');
            $data['describe'] = input('post.describe');
            $data['is_show'] = input('post.is_show');
            // 图片

            
            $file = request()->file('banner_img');
            if ($file) {
                
               $data['banner_img'] = handle_upload_image($file,'banner') ;


                // 原来图片地址
                $oldImgPath =AnnounceModel::getBannerInfoById($banner_id, 'banner_img');


            } 

            $data['add_time']=time();
            $bool = Db::table('banner')->where('banner_id',$banner_id)->update($data);

            if ($bool) {
                if (isset($oldImgPath) && !empty($oldImgPath['banner_img'])) {
                    unlink(get_image_url(AnnounceModel::BANNER_IMAGE_PATH,$oldImgPath['banner_img'],false));

                }
                 $this->success('修改成功', '/announce/BannerList');
            } else {
                $this->error('修改失败', '/announce/BannerEdit/id/'.$banner_id);
            }
        }
    }

    // 修改上线状态
    public function postAjaxChangeStatus(){
        if(request()->isAjax()){
            $id = input('post.id');
            $status = input('post.status');

            $announceModel = new \app\admin\model\AnnounceModel();
            $res = $announceModel->changeStatus($id, $status);

            return $res;
        }
    }

    // 已推送消息通知列表
    public function getPushMsgList(){

        $request = request();
        $search_type_of_time = $request->param('search_type_of_time', '');
        $atime = $request->param('atime', '');
        $ztime = $request->param('ztime', '');
        if (!$atime || !$ztime) {
            $search_type_of_time = '';
            $atime = '';
            $ztime = '';
        }
        if ($search_type_of_time == '') {
            $atime = '';
            $ztime = '';
        }

        $keyword = request()->param('keyword', '');
        $order_type = request()->param('order_type', 1);

        $this->msgList($keyword, $is_push = 2, $order_type, $push_status = 2, $search_type_of_time, $atime, $ztime);
        $this->assign([
            'keyword' => $keyword,
            'order_type' => $order_type,
            'search_type_of_time' => $search_type_of_time,
            'atime' => $atime,
            'ztime' => $ztime,

        ]);

        return $this->fetch('announce/pushMsgList');
    }

    private function msgList($keyword = "", $is_push=1, $order_type = '1', $push_status ,$search_type_of_time = '', $atime = '', $ztime = '' )
    {

        $where = '';
        if ($keyword) {
            
            $where['title'] = ['like', "%$keyword%"];
        }

        if ($order_type == 1) {
            $order_type = 'add_time desc';
        } else if($order_type == 2){
            $order_type = 'add_time ';
        } else if ($order_type == 3) {
            $order_type = 'push_time desc ';
        } else if($order_type == 4) {
            $order_type = 'push_time ';
        }

        $where['is_push']=$is_push;

        // 时间段搜索
        $oneday = 86400;
        if ($atime != '' && $search_type_of_time != '') {
            $atime = strtotime($atime);
        }

        if ($ztime != '' && $search_type_of_time != '') {
            $ztime = strtotime($ztime);
        }

        if ($search_type_of_time == 1) {

            $where['add_time'] = [['>', $atime], ['<', $ztime + $oneday], 'and'];
        } elseif ($search_type_of_time == 2) {

            $where['push_time'] = [['>', $atime], ['<', $ztime + $oneday], 'and'];
        } 


        $list = Db::table('push_message')->field(self::MESSAGE)->where($where)->order($order_type)->paginate(10);
        $page = $list->render();

        $msg_amount = Db('push_message')->where('is_push',$push_status)->count();



        $this->assign([
            'page' => $page,
            'list' => $list,
            'msg_amount' => $msg_amount
        ]);

    }

    // 未推送信息列表
    public function getDraftMsgList()
    {

        $keyword = request()->param('keyword', '');
        $order_type = request()->param('order_type', 1);

        $this->msgList($keyword,$is_push=1, $order_type , $push_status = 1  );

        $this->assign([
            'keyword' => $keyword,
            'order_type' => $order_type,
        ]);
        
        return $this->fetch('announce/draftList');
    }

    // 重新编辑消息
    public  function getMsgEdit(){
        $id=input('id');

        $AnnounceModel =new \app\admin\model\AnnounceModel();

        $info= $AnnounceModel->getMessageInfoById($id);

        $this->assign([
            'info'=>$info
        ]);
        return $this->fetch('announce/msgEdit');
    }

    public function postMsgEdit()
    {
        if (request()->isPost()) {
            $param = input('post.');

            $AnnounceModel = new \app\admin\model\AnnounceModel();
            $res = $AnnounceModel->updateMessage($param);

            if ($res) {
                $this->success('保存成功', '/announce/DraftMsgList');
            } else {
                $this->error('发生未知错误，保存失败', '/announce/MsgAdd');
            }
        }
    }



    // 新建消息
    public function getMsgAdd()
    {

        return $this->fetch('announce/msgAdd');
    }
    // 保存为草稿
    public function postMsgAdd(){
        if(request()->isPost()){

            if( input('post.title') == ''){
                $this->error('标题不能为空','/announce/MsgAdd');
            }
            if( input('post.content') == ''){
                $this->error('内容不能为空', '/announce/MsgAdd');
            }


            $param=input('post.');

            $AnnounceModel = new \app\admin\model\AnnounceModel();
            $res= $AnnounceModel ->saveMessage($param);

            if($res){
                $this->success('保存成功', '/announce/DraftMsgList');
            }else{
                $this->error('发生未知错误，保存失败', '/announce/MsgAdd');
            }
        }
    }
// 将message写入 客户待阅读表
    public function postMsgPush(){
        $msg_id=input('post.msg_id');

        $AnnounceModel = new \app\admin\model\AnnounceModel();
        $res = $AnnounceModel->pushMessage($msg_id);

        // var_dump($res);
        return $res?1:0;


    }



    // 删除未推送消息
    public function postMsgDel(){
        $id=input('post.id');

        $AnnounceModel = new \app\admin\model\AnnounceModel();

        $res = $AnnounceModel->deleteMessage($id);
        return $res;
    }

    
}
